import React, { useContext, useEffect, useRef } from 'react'
import ProList from '@ant-design/pro-list';
import ProForm, { ProFormSelect, ProFormCheckbox } from '@ant-design/pro-form';
import { Col, Row, Space, Button, message } from 'antd'
import styles from './index.less'
import { useState } from 'react';
import moment from 'moment';
import { ModalForm, ProFormTextArea } from '@ant-design/pro-form';
import { Popconfirm } from 'antd';
import { DeleteOutlined, FormOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import type { RecordsParams } from '@/services/records';
import { getAddRecords } from '@/services/records';
import { getEditRecords } from '@/services/records';
import { getRecordsInfo } from '@/services/records';
import { getDeleteItem } from '@/services/records';
import { getComRecordsList } from '@/services/records';
import { CourseContext } from '..';
import type { ActionType } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import { getStudentInfo } from '@/services/student';
import { history } from 'umi';
import { courseItemExport } from '@/services/situation';
export const duanOption = (v?: string) => {
  if (v == '8') {
    return '旧版i-0'
  } else if (v == '9') {
    return '启蒙零基础'
  } else if (v == '10') {
    return '启蒙进阶突破'
  } else if (v == '11') {
    return 'i-1'
  } else if (v == '12') {
    return 'i-2'
  } else if (v == '13') {
    return 'i-3'
  } else if (v == '14') {
    return 'i-4'
  } else if (v == '150') {
    return 'i-5'
  } else if (v == '160') {
    return 'i-6'
  } else if (v == '170') {
    return 'i-7'
  } else if (v == '180') {
    return 'i-8'
  } else if (v == '190') {
    return 'i-9'
  } else if (v == '200') {
    return 'i-10'
  } else if (v == '210') {
    return 'i-11'
  } else if (v == '220') {
    return 'i-12'
  } else {
    return '无段位'
  }
}
export default function Record() {
  const [option, setOption] = useState<any>();
  const [visible, setVisible] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [check, setChecked] = useState<any>(false);
  const [type, setType] = useState<number>();
  const [list, setList] = useState<RecordsParams[]>();
  const [itId, setItemId] = useState<string | undefined>();
  const ctx = useContext(CourseContext);

  const ref = useRef<ActionType>();
  const restFormRef = useRef<ProFormInstance>();
  const [dataInfo, setDataInfo] = useState<any>()
  const [itemInfo, setItemInfo] = useState<RecordsParams>()
  const onConfirm = async (itemId?: string) => {
    const res = await getDeleteItem({ id: itemId });
    if (res.success) {
      message.success('删除成功')
      ref.current?.reload();
    }
  }
  const { id } = history.location.query ?? {}
  useEffect(() => {
    (async () => {
      const res = await getStudentInfo({ id: ctx.id });
      setDataInfo(res.result);
    })();
  }, [ctx])

  const showObject = (e?: string) => {
    if (e == '1') { return '爸爸' }
    else if (e == '2') { return '妈妈' }
    else if (e == "3") { return '爷爷' }
    else if (e == '4') { return '奶奶' }
    else if (e == '5') { return '姥姥' }
    else if (e == '6') { return '姥爷' }
    else if (e == '7') { return '其他' }
    else { return '-' }
  }
  const showPurpose = (ee?: string) => {
    if (ee == '1') { return '日常沟通' }
    else if (ee == '2') { return '续报沟通' }
    else if (ee == '3') { return '退费沟通' }
    else if (ee == '4') { return '特殊情况沟通' }
    else { return; }
  }
  const goEditItem = async (i?: string) => {
    const res = await getRecordsInfo({ id: i })
    if (res?.success) {
      setItemInfo(res?.result)
    }
    setType(1);
    setVisible(true);
    setItemId(i);
  }
  const exportsRecords = async () => {
    if (list?.length == 0) {
      message.error('没有可导出的数据')
      return;
    }
    setLoading(true)
    let param;
    if (check) {
      param = {
        onlyLookMine: 1,
        purpose: option,
        uid: ctx.uid,
        checkRole: 1,
      }
    } else {
      param = {
        uid: ctx.uid,
        checkRole: 1,
        purpose: option,
      }
    }
    await courseItemExport({
      exportType: 'exportCourseUserCommunicates',
      map: {
        ...param
      },
      fileName: `${dataInfo?.nickname || ''}_沟通记录.xlsx`

    });
    setLoading(false)
  }

  return (
    <div className={styles.right_wrap}>
      <Row className={styles.right_pro_form_style}>
        <Col span={12}>
          <ProForm
            layout="horizontal"
          >
            <ProFormSelect
              colProps={{ xl: 8, md: 12 }}
              label="沟通目的："
              name="required"
              initialValue="0"
              fieldProps={{
                onChange: (val) => setOption(val == 0 ? undefined : val),
                allowClear: false,
                autoFocus: false
              }}
              valueEnum={{
                0: '全部',
                1: '日常沟通',
                2: '续报沟通',
                3: '退费沟通',
                4: '特殊情况沟通',
              }}
            />
          </ProForm>
        </Col>
        <Col span={12} className={styles.checkbox}>
          <ProFormCheckbox
            name="checkbox"
            fieldProps={{
              onChange: (e) => setChecked(e.target.checked)
            }}
          />
          &nbsp;
          <div style={{ marginTop: '-7px' }}>只看我的</div>
        </Col>
      </Row>
      <Row justify="end" style={{ marginTop: '10px' }}>
        <Space>
          <Button loading={loading} onClick={exportsRecords}>导出</Button>
          <Button type="primary" onClick={() => {
            setVisible(true); setType(2);
          }}>添加</Button>
        </Space>
      </Row>
      <ProList<RecordsParams>
        className={styles.pro_list}
        pagination={{
          hideOnSinglePage: true,
          simple: true,
          defaultPageSize: 2,
        }}
        actionRef={ref}
        itemLayout="vertical"
        rowKey="id"
        params={{
          purpose: option,
          uid: ctx.uid,
          check: check,
          onlyLookMine: 1,
          checkRole: 1,
        }}
        request={async (params) => {
          (params as any).currentPage = params.current
          delete (params.current)
          delete (params.check)
          if (!check) {
            delete (params.onlyLookMine)
          }
          const dd = await getComRecordsList({ ...params })
          setList(dd?.result?.records)
          return {
            data: dd?.result?.records,
            total: dd?.result?.total
          }
        }}
        renderItem={(item) => (
          <div className={styles.connect_item}>
            <Row justify="space-between">
              <div>{item.createUserName} &nbsp;<span className={styles.font_style}>{moment(item.createTime).format('YYYY.MM.DD HH:mm')}</span></div>
              <div className={styles.tips_style}>{showPurpose(item.purpose)}</div>
            </Row>

            <div className={styles.font_style}>沟通对象：{showObject(item.object)}</div>
            <div style={{ margin: '8px 0' }}>{`${item.courseName || ''} ${item.duan ? '（' : ''}${duanOption(item.duan) || ''}${item.duan ? '）' : ''}`}</div>
            <div>沟通内容：</div>
            <Row>
              <Col span={20}>
                <div>{item.content}</div>
              </Col>
              <Col span={4}>
                <Space>
                  {
                    item?.createUser == localStorage.getItem('teacherId') && id == item.courseId ?
                      <a onClick={() => goEditItem(item.id)}>
                        <div style={{ display: 'inline-block', width: '30px', height: '30px' }}>

                          <FormOutlined className={styles.svg_style} />
                        </div>
                      </a> : null
                  }
                  {
                    item?.createUser == localStorage.getItem('teacherId') && id == item.courseId ?
                      <Popconfirm
                        placement="topRight"
                        title="确定要删除吗？"
                        onCancel={() => { message.info('您取消了删除') }}
                        onConfirm={() => onConfirm(item.id)}
                        icon={<QuestionCircleOutlined
                          style={{ color: 'red' }}
                        />}>
                        <a><DeleteOutlined className={styles.svg_style} /></a>
                      </Popconfirm> : null
                  }
                </Space>
              </Col>
            </Row>
          </div>
        )}
      />

      <ModalForm
        title={type == 1 ? '编辑沟通记录' : '添加沟通记录'}
        submitter={{
          searchConfig: {
            submitText: '确认',
            resetText: '取消',
          },
        }}
        formRef={restFormRef}

        modalProps={{
          destroyOnClose: true,
        }}

        layout="horizontal"
        visible={visible}
        onVisibleChange={(val) => {
          setVisible(val)
        }}
        onFinish={async (values) => {
          if (type == 1) {
            const res = await getEditRecords({ ...values, id: itId, courseId: ctx.courseId })
            if (res.success) {
              message.success('编辑成功');
              setVisible(false)
              ref.current?.reload();
            }
          } else {
            const res = await getAddRecords({
              ...values, courseId: ctx.courseId, uid: ctx.uid
            })
            if (res.success) {
              message.success('添加成功')
              setVisible(false)
              ref.current?.reload();
            }
          }
        }}
      >
        <div style={{ width: '50%', margin: 'auto' }}>
          <ProFormSelect
            name="object"
            label="沟通对象"
            width="md"
            fieldProps={{
              // onChange: (val) => handleChange(val)
            }}
            initialValue={type == 1 ? itemInfo?.object ?? "0" : '0'}
            params={{

            }}
            valueEnum={{
              0: '请选择',
              1: "爸爸",
              2: "妈妈",
              3: "爷爷",
              4: "奶奶",
              5: "姥姥",
              6: "姥爷",
              7: "其他",
            }}
            rules={[{ required: true, message: '请选择沟通对象' }
              , { pattern: /^[1-9]$/, message: '请选择沟通目的' }
            ]}
          />
          <ProFormSelect
            name="purpose"
            label="沟通目的"
            width="md"
            fieldProps={{
              // onChange: (val) => handleChange(val)
            }}
            initialValue={type == 1 ? itemInfo?.purpose ?? '0' : '0'}
            params={{

            }}
            valueEnum={{
              0: '请选择',
              1: "日常沟通",
              2: "续报沟通",
              3: "退费沟通",
              4: "特殊情况沟通",
            }}
            rules={[
              { required: true, message: '请选择沟通目的' },
              { pattern: /^[1-9]$/, message: '请选择沟通目的' }
            ]}
          />
          <ProFormTextArea
            name="content"
            label="沟通内容"
            placeholder="请输入名称"
            fieldProps={{
              showCount: true, maxLength: 500, placeholder: "请输入沟通内容",
            }}
            initialValue={type == 1 ? itemInfo?.content : ''}
            rules={[{ required: true, message: '请输入沟通内容' }]}

          />
        </div>
      </ModalForm>
    </div>
  )
}
